package com.example.demo.realm;

import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
//import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.demo.entify.Menu;
import com.example.demo.entify.Role;
import com.example.demo.entify.User;
import com.example.demo.service.UserRoleService;
import com.example.demo.service.UserService;

public class WJRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	private UserRoleService userRoleService;

    // 简单重写获取授权信息方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        
        // 获取身份信息
        String primaryPrincipalString = (String) principalCollection.getPrimaryPrincipal();
       User user = userRoleService.findRoleByname(primaryPrincipalString);
       if(!CollectionUtils.isEmpty((Collection) user.getRoles())) {
    	   
    	   SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
    	   System.out.println(user.getRoles());
    	   s.addRole(user.getRoles().getNameZh());
    	   System.out.println(user.getRoles().getNameZh());
    	   List<Role> menus = userRoleService.findMenuByname(user.getRoles().getId());
    	   if (menus!=null) {
    		   menus.forEach(menu->{    			   
    			   s.addStringPermission(menu.getName());    		     
    		   });			
		}
    	   return s;
       }	
        return null;
        
    }

    // 获取认证信息，即根据 token 中的用户名从数据库中获取密码、盐等并返回
 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
       User user = userService.findByUsername(userName);
        String passwordInDB = user.getPassword();
        String salt = user.getSalt();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, passwordInDB, ByteSource.Util.bytes(salt), getName());
        return authenticationInfo;
    }
}


